package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    /**
     * 根据分类id查询品牌
     *
     * @param cid
     * @return
     */
    @Override
    public List<BrandDTO> queryBrandByCatagoryId(Long cid) {
        //1.根据分类id查询品牌id
        List<CategoryBrand> list = categoryBrandService.query().eq("category_id", cid).list();
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }

        //2.获得brandIds
        List<Long> brandIds = list.stream().map(CategoryBrand::getBrandId).collect(Collectors.toList());

        //3.根据获得brandIds获取品牌信息
        List<Brand> brands = this.listByIds(brandIds);
        return BrandDTO.convertEntityList(brands);
    }

    /**
     * 分页查询品牌
     *
     * @param key
     * @param page
     * @param rows
     * @return
     */
    @Override
    public PageDTO<BrandDTO> queryBrandByPage(String key, Long page, Long rows) {
        //1,创建Page对象
        Page<Brand> info = new Page<>(page, rows);

        //2.判断key是否存在
        boolean isKeyExists = StringUtils.isNotBlank(key);
        //如果存在进行模糊查询
        this.query()
            .like(isKeyExists,"name", key)
            .or()
            .eq(isKeyExists,"letter", key)
            .page(info);

        //获取当前页查询的品牌集合
        List<Brand> brandList = info.getRecords();
        return new PageDTO<BrandDTO>(info.getTotal(), info.getPages(), BrandDTO.convertEntityList(brandList));

    }

    /**
     * 根据id删除品牌
     * @param id
     */
    @Transactional
    @Override
    public void deleteBrandById(Long id) {
        //TODO:要删除品牌必须先检查品牌是否有用，如果有用，拒绝删除
        if (this.removeById(id)) {
            deleteCategoryBrandByBrandId(id);
        }
    }

    private void deleteCategoryBrandByBrandId(Long id) {
        categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", id));
    }

    /**
     * 新增品牌
     * @param brandDTO
     */
    @Transactional
    @Override
    public void saveBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        this.save(brand);

        // 封装中间表对象的集合
        saveCategoryBrand(brandDTO.getCategoryIds(), brand.getId());
    }

    private void saveCategoryBrand(List<Long> categoryIds, Long bid) {
        List<CategoryBrand> list = categoryIds.stream()
                .map(cid -> CategoryBrand.of(cid, bid))
                .collect(Collectors.toList());

        //批量保存中间表
        categoryBrandService.saveBatch(list);
    }

    @Transactional
    @Override
    public void updateBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        if (this.updateById(brand)){
            //删除中间表关系,然后重建
            deleteCategoryBrandByBrandId(brand.getId());

            //重建品牌及分类的之间的关系
            saveCategoryBrand(brandDTO.getCategoryIds(),brand.getId());
        }
    }
}
